
import React, { useState, useEffect, createRef } from 'react'
import styles from '../../style/childPublic/childPublic.module.less'
import business from '../../style/BusinessEntity/BusinessEntity.module.less'
import HeaderTop from "../../components/HeaderTop/HeaderTop";
import LeftNav from '../../components/LeftNav/LeftNav';
import { SearchOutlined } from '@ant-design/icons';
import { useNavigate, useLocation } from "react-router-dom";
import { Input, Button, Pagination, message, Empty } from 'antd';
import { getArea } from '../../apis/businessEntity'
export default function BusinessEntity() {
    const [title] = useState('经营主体信息监管平台');
    const [messageApi, contextHolder] = message.useMessage();
    const key = 'updatable';
    // 获取传递过来的数据
    const { state } = useLocation();
    const [leftNavList, setLeftNavList] = useState([])
    const [currentId, setCurrentId] = useState('')

    const [titleSite, setTitleSite] = useState('全部')
    const [topNavList] = useState([
        { title: '已记账' },
        { title: '未记账' },
        { title: '全部记账' },
    ])
    const [contentListTitle] = useState([
        { id: 1, title: '联系人' },
        { id: 2, title: '联系电话' },
        { id: 3, title: '挂靠公司' },
        { id: 4, title: '农药经营许可证' },
        { id: 5, title: '地址' },
        { id: 6, title: '台账报送情况' },
        { id: 7, title: '记账情况' },
    ])
    const [contentList, setContentList] = useState([])
    const [currentTitle, setCurrentTitle] = useState('全部记账')
    const navigate = useNavigate()
    // 顶部已入账未入账状态切换
    const changeShow = (title) => {
        const newCurrentTitle = topNavList.filter(item => item.title === title)
        setCurrentTitle(newCurrentTitle[0].title)
        switch (title) {
            case '已记账':
                setAreaData({ ...areaData, record_state: 'yes', pageNum: 1 })
                break;
            case '未记账':
                setAreaData({ ...areaData, record_state: 'no', pageNum: 1 })
                break;
            default:
                setAreaData({ ...areaData, record_state: '', pageNum: 1 })
                break;
        }
    }
    const keyWordsRef = createRef();
    const [keyWords, setKeyWords] = useState('')
    const [areaData, setAreaData] = useState({ pageNum: 1, pageSize: '10', area_level: localStorage.getItem('areaLevel'), area_id: localStorage.getItem('areaId'), keywords: '', record_state: '' })
    const [total, setTotal] = useState(0)

    useEffect(() => {
        HomeDate(areaData)
    }, [areaData])
    const HomeDate = async (res) => {
        messageApi.open({
            key,
            type: 'loading',
            content: '数据加载中...',
        });
        const { data } = await getArea(res)
        if (data.state === 1) {
            let newArray = []
            let newObject = { name: '全部', id: Number(localStorage.getItem('areaId')), area_level: localStorage.getItem('areaLevel') }
            newArray = [...data.areaList, newObject]
            newArray.reverse()
            setLeftNavList(newArray)
            setContentList(data.list)
            setTotal(data.count)
            messageApi.open({
                key,
                type: 'success',
                content: '数据加载完成!',
                duration: 2,
            });
        } else {
            messageApi.open({
                key,
                type: 'error',
                content: data.msg,
                duration: 2,
            });
        }
    }
    // 侧边栏
    const getClick = (data) => {
        setTitleSite(data.name)
        setCurrentId(data.id)
        setAreaData({
            ...areaData,
            pageNum: 1,
            area_level: data.area_level,
            area_id: data.id
        })
    }
    // 搜索
    const search = () => {
        setAreaData({ ...areaData, pageNum: 1, keywords: keyWords })
    }
    // 分页
    const itemRender = (_, type, originalElement) => {
        if (type === 'prev') {
            return <a>上一页</a>;
        }
        if (type === 'next') {
            return <a>下一页</a>;
        }
        return originalElement;
    };
    // 切换页码
    const onChangePage = (page) => {
        setAreaData({
            ...areaData,
            pageNum: page
        })
    }
    // 查看台账
    const getLedgerDetails = (id) => {
        navigate('/LedgerDetails', { state: { id } })
    }
    return (
        <div className={styles.pubBack}>
            {contextHolder}
            <HeaderTop title={title}></HeaderTop>
            <div className={business.contentBox}>
                {/* 左侧乡镇列表 */}
                <div className={business.leftBox}>
                    <LeftNav leftNavList={leftNavList} currentId={currentId} getClick={getClick}></LeftNav>
                </div>
                {/* 右侧内容区 */}
                <div className={business.right}>
                    <span className={business.topTitle}>农药经营主体信息列表</span>
                    <div className={business.content}>
                        {/* 经营主体 */}
                        <div className={business.entity}>
                            <span>经营主体</span>
                            <span>{total}
                                <i>家</i>
                            </span>
                        </div>
                        {/* 筛选 */}
                        <div className={business.search}>
                            <div className={business.leftList}>
                                <span>{titleSite}</span>
                                <ul>
                                    {
                                        topNavList.map(item => {
                                            return (
                                                <li key={item.title} onClick={() => changeShow(item.title)}>
                                                    <span className={currentTitle === item.title ? `${business.show}` : ''}>{item.title}</span>
                                                </li>
                                            )
                                        })
                                    }
                                </ul>
                            </div>
                            <div className={business.rightList}>
                                <Input type="text" ref={keyWordsRef} value={keyWords} onChange={() => {
                                    setKeyWords(keyWordsRef.current.input.value)
                                }} placeholder="请输入联系人名称/电话查询" />
                                <Button type="primary" onClick={() => search()} icon={<SearchOutlined />}>
                                    查询
                                </Button>
                            </div>
                        </div>
                        {/* 列表 */}
                        <div className={business.listBox}>
                            <table>
                                <thead>
                                    {
                                        contentListTitle.map(item => {
                                            return (
                                                <th key={item.id}>{item.title}  </th>
                                            )
                                        })
                                    }
                                </thead>
                                <tbody className={contentList.length !== 0 ? "" : `${business.noShowData}`}>
                                    {
                                        contentList.map(item => {
                                            return (
                                                <tr key={item.user_id}>
                                                    <td>{item.name === undefined || item.name === '' ? '暂无数据' : item.name}</td>
                                                    <td>{item.mobile === undefined || item.mobile === '' ? '暂无数据' : item.mobile}</td>
                                                    <td>{item.aff_company === undefined || item.aff_company === '' ? '未填写' : item.aff_company}</td>
                                                    <td>{item.licence_img === undefined ? "未上传" : '已上传'}</td>
                                                    <td>{item.address === undefined || item.address === '' ? "未填写" : item.address}</td>
                                                    <td onClick={() => getLedgerDetails(item.user_id)}>查看台账</td>
                                                    {
                                                        item.record_time !== 0 ?
                                                            <td className={item.record_time > 0 ? `${business.noWrite}` : ''}>{item.record_time < 0 ? `${Math.abs(item.record_time)}天前已做账` : '未做账'}</td> :
                                                            <td>今日已做账</td>
                                                    }
                                                </tr>
                                            )
                                        })
                                    }
                                </tbody>
                                <tr className={contentList.length === 0 ? `${business.emptyData}` : `${business.noShowData}`}>
                                    <td colSpan={7} style={{ textAlign: 'center' }}>
                                        <Empty
                                            image="http://120.79.70.96:10301/mapimg/kong_he.png"
                                            imageStyle={{
                                                height: 150,
                                            }} />
                                    </td>
                                </tr>
                            </table>
                        </div>
                    </div>
                    {/* 页尾 */}
                    <div className={business.pagActive}>
                        <Pagination total={total} current={areaData.pageNum} defaultCurrent={1} showTotal={(total) => `共 ${total} 条记录`} itemRender={itemRender} pageSize={10} onChange={onChangePage} showSizeChanger={false} />
                    </div>
                </div>
            </div>
        </div>
    )
}
